﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Training.Library.Interfaces;
using Training.Library.DomainObject.Administration.Catalog;
using System.Data.SqlClient;
using System.Data;
using Training.Library.Enum;
using SIPO.Library.DomainObject.Administration.Catalog;

namespace Training.Library.DataAccess.Administration.Catalog
{
    public partial class LokasiRepo : ISearchable<Lokasi>
    {
        public List<Lokasi> GetList(int pageSize, int currentPage, string sortName, string sortOrder,string parameters)
        {
            List<Lokasi> tt = new List<Lokasi>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    int startRow = ((currentPage - 1) * pageSize) + 1;
                    int endRow = (startRow + pageSize);

                    //StringBuilder sbQuery = new StringBuilder();
                    //sbQuery.AppendFormat(" WITH result_set AS ");
                    //sbQuery.AppendFormat(" ( ");
                    //sbQuery.AppendFormat("    SELECT ");
                    //sbQuery.AppendFormat("      ROW_NUMBER() OVER (ORDER BY {0} {1}) AS [row_number], ", sortName, sortOrder);
                    //sbQuery.AppendFormat("      Lokasi.LokasiID, Lokasi.NamaLokasi, Lokasi.CreatedDate, Lokasi.CreatedBy, Lokasi.UpdatedDate, Lokasi.UpdatedBy,Cabang.NamaCabang ");
                    //sbQuery.AppendFormat("    FROM ");
                    //sbQuery.AppendFormat("      master.Lokasi LEFT JOIN master.Cabang ON Lokasi.CabangID = Cabang.CabangID ");
                    //sbQuery.AppendFormat("      {0} ",parameters);
                    //sbQuery.AppendFormat(" ) ");
                    //sbQuery.AppendFormat(" SELECT * FROM result_set WHERE [row_number] BETWEEN {0} AND {1} ", startRow, endRow);

                    //cmd.CommandText = sbQuery.ToString();
                    //cmd.CommandType = CommandType.Text;

                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "SP_Lokasi_GridPage";
                    cmd.Parameters.Add("@startRow", SqlDbType.Int).Value = startRow;
                    cmd.Parameters.Add("@endRow", SqlDbType.Int).Value = endRow;
                    cmd.Parameters.Add("@sortName", SqlDbType.VarChar).Value = sortName;
                    cmd.Parameters.Add("@sortOrder", SqlDbType.VarChar).Value = sortOrder;
                    cmd.Parameters.Add("@param", SqlDbType.VarChar).Value = parameters;

                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                Lokasi t = new Lokasi(true);
                                t.LokasiID = dr[Lokasi.Fields.LokasiID] == DBNull.Value ? 0 : int.Parse(dr[Lokasi.Fields.LokasiID].ToString());
                                t.NamaLokasi = dr[Lokasi.Fields.NamaLokasi] == DBNull.Value ? string.Empty : dr[Lokasi.Fields.NamaLokasi].ToString();
                                t.CreatedDate = dr[Lokasi.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[Lokasi.Fields.CreatedDate].ToString());
                                t.CreatedBy = dr[Lokasi.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[Lokasi.Fields.CreatedBy].ToString();
                                t.UpdatedDate = dr[Lokasi.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[Lokasi.Fields.UpdatedDate].ToString());
                                t.UpdatedBy = dr[Lokasi.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[Lokasi.Fields.UpdatedBy].ToString();

                                t.Cabang.NamaCabang = dr[Cabang.Fields.NamaCabang] == DBNull.Value ? string.Empty : dr[Cabang.Fields.NamaCabang].ToString();

                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }

        public object SelectScalar(SQL.Function.Aggregate function, string column,string parameters)
        {
            object _result = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    StringBuilder sbQuery = new StringBuilder();
                    switch (function)
                    {
                       
                        case SQL.Function.Aggregate.Count:
                            //sbQuery.AppendFormat("SELECT COUNT({0}) FROM master.Lokasi {0}", column,parameters);
                            cmd.CommandText = "SP_Lokasi_GridPage_CountData";
                            break;
                      
                        default:
                            // do nothing 
                            break;
                    }

                    //cmd.CommandText = sbQuery.ToString();
                    //cmd.CommandType = CommandType.Text;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@column", SqlDbType.VarChar).Value = column;
                    cmd.Parameters.Add("@param", SqlDbType.VarChar).Value = parameters;
                    try
                    {
                        conn.Open();
                        _result = cmd.ExecuteScalar();
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return _result;
        }

        public bool SaveUpload(List<Lokasi> list)
        {
            bool result = false;

            using (SqlConnection conn = new SqlConnection(connectionString))
            {

                conn.Open();
                SqlTransaction txn = conn.BeginTransaction();
                try
                {

                    foreach (Lokasi data in list)
                    {
                        #region Filter By NamaCabang

                        string query = @"SELECT COUNT(NamaLokasi) FROM master.LOKASI WHERE NamaLokasi=@NamaLokasi";
                        SqlCommand cmdCount = new SqlCommand(query, conn);
                        cmdCount.Parameters.Add("@NamaLokasi", SqlDbType.VarChar).Value = data.NamaLokasi;

                        cmdCount.Transaction = txn;
                        var jumlah = cmdCount.ExecuteScalar();
                        int resultJumlah = jumlah == DBNull.Value ? 0 : int.Parse(jumlah.ToString());
                        cmdCount.Dispose();

                        #endregion

                        #region Insert Data Cabang Jika Tidak Ada
                        if (resultJumlah == 0)
                        {
                            query = "SP_Lokasi_Insert";
                            SqlCommand cmd = new SqlCommand(query, conn);
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.CommandTimeout = 0;
                            cmd.Parameters.Add("@NamaLokasi", SqlDbType.VarChar).Value = (object)data.NamaLokasi ?? DBNull.Value;
                            cmd.Parameters.Add("@CabangID", SqlDbType.Int).Value = (object)data.CabangID ?? DBNull.Value;
                            cmd.Parameters.Add("@CreatedDate", SqlDbType.DateTime).Value = (object)data.CreatedDate ?? DBNull.Value;
                            cmd.Parameters.Add("@CreatedBy", SqlDbType.VarChar).Value = (object)data.CreatedBy ?? DBNull.Value;
                            cmd.Parameters.Add("@UpdatedDate", SqlDbType.DateTime).Value = (object)data.UpdatedDate ?? DBNull.Value;
                            cmd.Parameters.Add("@UpdatedBy", SqlDbType.VarChar).Value = (object)data.UpdatedBy ?? DBNull.Value;

                            cmd.Transaction = txn;
                            cmd.ExecuteNonQuery();
                            cmd.Dispose();
                        }
                        #endregion
                    }




                    result = true;
                    txn.Commit();

                }
                catch (Exception ex)
                {
                    txn.Rollback();
                    throw (ex);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open) conn.Close();
                }
            }

            return result;
        }
    }
}
